package com.dylan.历史.多线程.并发编程的艺术;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Dylan on 2018/9/6.
 */
public class 并发_CAS {

    private static int i = 0;
    private static AtomicInteger atomicI = new AtomicInteger(0);

    /**
     * 下面是基于CAS线程安全的计数器
     */
    public static void main(String[] args) {
        // 使用线程并发
        List<Thread> list = new ArrayList<>(1000);
        for (int i = 0; i < 200; i++) {
            list.add(new Thread() {
                @Override
                public void run() {
                    for (int k = 0; k < 10000; k++) {
                        count1();
                        count2();
                    }
                }
            });
        }
        // 启动所有线程
        for (Thread t : list) {
            t.start();
        }
        // 等待所有线程执行完
        for (Thread t : list) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 打印计数器结果
        System.out.println(i);
        System.out.println(atomicI.get());
    }

    // 非线程安全的计数器
    private static void count1() {
        i++;
    }

    // 线程安全的计数器
    private static void count2() {
        while (true) {
            int j = atomicI.get();
            boolean success = atomicI.compareAndSet(j, ++j);
            if (success) {
                break;
            }
        }
    }

}
